/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.transaction.core.util;


import com.lvyh.lightframe.transaction.common.exception.TransactionRuntimeException;
import com.lvyh.lightframe.transaction.common.thread.NamedThreadFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Thread pool tool
 */
public class ThreadPoolUtils {

    public static int THREAD_PRIORITY_NORMAL = 0;

    public static int THREAD_PRIORITY_HIGH = 10;

    public static int THREAD_PRIORITY_LOW = -10;


    public static ThreadPoolExecutor newFixedThreadPool(int corePoolSize) {
        return new ThreadPoolExecutor(corePoolSize,
                corePoolSize,
                0,
                TimeUnit.MILLISECONDS,
                new SynchronousQueue<Runnable>());
    }


    public static ThreadPoolExecutor newFixedThreadPool(int corePoolSize,
                                                        BlockingQueue<Runnable> queue) {
        return new ThreadPoolExecutor(corePoolSize,
                corePoolSize,
                0,
                TimeUnit.MILLISECONDS,
                queue);
    }


    public static ThreadPoolExecutor newFixedThreadPool(int corePoolSize,
                                                        BlockingQueue<Runnable> queue,
                                                        ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(corePoolSize,
                corePoolSize,
                0,
                TimeUnit.MILLISECONDS,
                queue,
                threadFactory);
    }


    public static ThreadPoolExecutor newFixedThreadPool(int corePoolSize,
                                                        BlockingQueue<Runnable> queue,
                                                        ThreadFactory threadFactory,
                                                        RejectedExecutionHandler handler) {
        return new ThreadPoolExecutor(corePoolSize,
                corePoolSize,
                0,
                TimeUnit.MILLISECONDS,
                queue,
                threadFactory,
                handler);
    }


    public static ThreadPoolExecutor newCachedThreadPool(int corePoolSize,
                                                         int maximumPoolSize) {
        return new ThreadPoolExecutor(corePoolSize,
                maximumPoolSize,
                DateUtils.MILLISECONDS_PER_MINUTE,
                TimeUnit.MILLISECONDS,
                new SynchronousQueue<Runnable>());
    }


    public static ThreadPoolExecutor newCachedThreadPool(int corePoolSize,
                                                         int maximumPoolSize,
                                                         BlockingQueue<Runnable> queue) {
        return new ThreadPoolExecutor(corePoolSize,
                maximumPoolSize,
                DateUtils.MILLISECONDS_PER_MINUTE,
                TimeUnit.MILLISECONDS,
                queue);
    }


    public static ThreadPoolExecutor newCachedThreadPool(int corePoolSize,
                                                         int maximumPoolSize,
                                                         BlockingQueue<Runnable> queue,
                                                         ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(corePoolSize,
                maximumPoolSize,
                DateUtils.MILLISECONDS_PER_MINUTE,
                TimeUnit.MILLISECONDS,
                queue,
                threadFactory);
    }


    public static ThreadPoolExecutor newCachedThreadPool(int corePoolSize,
                                                         int maximumPoolSize,
                                                         BlockingQueue<Runnable> queue,
                                                         ThreadFactory threadFactory,
                                                         RejectedExecutionHandler handler) {
        return new ThreadPoolExecutor(corePoolSize,
                maximumPoolSize,
                DateUtils.MILLISECONDS_PER_MINUTE,
                TimeUnit.MILLISECONDS,
                queue,
                threadFactory,
                handler);
    }


    public static ThreadPoolExecutor newCachedThreadPool(int corePoolSize,
                                                         int maximumPoolSize,
                                                         int keepAliveTime,
                                                         BlockingQueue<Runnable> queue,
                                                         ThreadFactory threadFactory,
                                                         RejectedExecutionHandler handler) {
        return new ThreadPoolExecutor(corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                TimeUnit.MILLISECONDS,
                queue,
                threadFactory,
                handler);
    }

    public static ScheduledExecutorService newScheduledThreadPool(String name) {
        return Executors.newScheduledThreadPool(2, new NamedThreadFactory(name));
    }


    public static BlockingQueue<Runnable> buildQueue(int size) {
        return buildQueue(size, false);
    }


    public static BlockingQueue<Runnable> buildQueue(int size, boolean isPriority) {
        BlockingQueue<Runnable> queue;
        if (size == 0) {
            queue = new SynchronousQueue<Runnable>();
        } else {
            if (isPriority) {
                queue = size < 0 ? new PriorityBlockingQueue<Runnable>()
                        : new PriorityBlockingQueue<Runnable>(size);
            } else {
                queue = size < 0 ? new LinkedBlockingQueue<Runnable>()
                        : new LinkedBlockingQueue<Runnable>(size);
            }
        }
        return queue;
    }


    public static ThreadPoolExecutor makeServerThreadPool(final String serverType, int corePoolSize, int maxPoolSize) {
        ThreadPoolExecutor serverHandlerPool = new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                60L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(1000),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, "Transaction, " + serverType + "-ServerThreadPool-" + r.hashCode());
                    }
                },
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        throw new TransactionRuntimeException("Transaction " + serverType + " Thread pool is EXHAUSTED!");
                    }
                });

        return serverHandlerPool;
    }

}
